const Router = require('@koa/router');
const { Article, User, Comment } = require('../databases');

const articleRouter = new Router({
    prefix: '/article'
});

// 获取文章首页
articleRouter.get('/', (ctx, next) => {
    ctx.body = {
        code: 200,
        message: '文章首页',
        data: 'Welcome to article API',
    };
});

// 创建文章
articleRouter.post('/create', async (ctx, next) => {
    try {
        const { uid, title, content, summary, coverImage, category, tags } = ctx.request.body;
        
        // 验证用户是否存在
        const user = await User.findByPk(uid);
        if (!user) {
            ctx.body = {
                code: 404,
                message: '用户不存在',
                data: null
            };
            return;
        }

        const article = await Article.create({
            uid,
            title,
            content,
            summary,
            coverImage,
            category,
            tags,
            status: 'draft'
        });

        ctx.body = {
            code: 200,
            message: '创建文章成功',
            data: article,
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '创建文章失败',
            error: error.message
        };
    }
});

// 获取所有已发布的文章列表
articleRouter.get('/list', async (ctx, next) => {
    try {
        const { page = 1, limit = 10, category, status = 'published' } = ctx.query;
        const offset = (page - 1) * limit;
        
        let whereCondition = { status };
        if (category) {
            whereCondition.category = category;
        }

        const { count, rows: articles } = await Article.findAndCountAll({
            where: whereCondition,
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['uid', 'username']
                }
            ],
            order: [['createAt', 'DESC']],
            limit: parseInt(limit),
            offset: parseInt(offset)
        });
        
        ctx.body = {
            code: 200,
            message: '获取文章列表成功',
            data: {
                articles,
                total: count,
                page: parseInt(page),
                limit: parseInt(limit),
                totalPages: Math.ceil(count / limit)
            },
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '获取文章列表失败',
            error: error.message
        };
    }
});

// 根据ID获取文章详情
articleRouter.get('/:id', async (ctx, next) => {
    try {
        const { id } = ctx.params;
        const article = await Article.findByPk(id, {
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['uid', 'username']
                },
                {
                    model: Comment,
                    as: 'comments',
                    include: [
                        {
                            model: User,
                            as: 'user',
                            attributes: ['uid', 'username']
                        }
                    ],
                    where: { status: 'active' },
                    required: false
                }
            ]
        });

        if (!article) {
            ctx.body = {
                code: 404,
                message: '文章不存在',
                data: null
            };
            return;
        }

        // 增加浏览次数
        await article.increment('viewCount');

        ctx.body = {
            code: 200,
            message: '获取文章详情成功',
            data: article,
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '获取文章详情失败',
            error: error.message
        };
    }
});

// 更新文章
articleRouter.put('/:id', async (ctx, next) => {
    try {
        const { id } = ctx.params;
        const { title, content, summary, coverImage, category, tags, status } = ctx.request.body;

        const article = await Article.findByPk(id);
        if (!article) {
            ctx.body = {
                code: 404,
                message: '文章不存在',
                data: null
            };
            return;
        }

        const updateData = {
            title: title || article.title,
            content: content || article.content,
            summary: summary || article.summary,
            coverImage: coverImage || article.coverImage,
            category: category || article.category,
            tags: tags || article.tags,
            updateAt: new Date()
        };

        // 如果状态从草稿变为发布，设置发布时间
        if (status === 'published' && article.status === 'draft') {
            updateData.publishAt = new Date();
        }
        if (status) {
            updateData.status = status;
        }

        await article.update(updateData);

        ctx.body = {
            code: 200,
            message: '更新文章成功',
            data: article,
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '更新文章失败',
            error: error.message
        };
    }
});

// 删除文章
articleRouter.delete('/:id', async (ctx, next) => {
    try {
        const { id } = ctx.params;
        
        const article = await Article.findByPk(id);
        if (!article) {
            ctx.body = {
                code: 404,
                message: '文章不存在',
                data: null
            };
            return;
        }

        await article.destroy();

        ctx.body = {
            code: 200,
            message: '删除文章成功',
            data: null,
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '删除文章失败',
            error: error.message
        };
    }
});

// 根据用户ID获取文章列表
articleRouter.get('/user/:userId', async (ctx, next) => {
    try {
        const { userId } = ctx.params;
        const { status } = ctx.query;
        
        const user = await User.findByPk(userId);
        if (!user) {
            ctx.body = {
                code: 404,
                message: '用户不存在',
                data: null
            };
            return;
        }

        let whereCondition = { uid: userId };
        if (status) {
            whereCondition.status = status;
        }

        const articles = await Article.findAll({
            where: whereCondition,
            order: [['createAt', 'DESC']]
        });

        ctx.body = {
            code: 200,
            message: '获取用户文章列表成功',
            data: articles,
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '获取用户文章列表失败',
            error: error.message
        };
    }
});

// 根据分类获取文章列表
articleRouter.get('/category/:category', async (ctx, next) => {
    try {
        const { category } = ctx.params;
        const { page = 1, limit = 10 } = ctx.query;
        const offset = (page - 1) * limit;

        const { count, rows: articles } = await Article.findAndCountAll({
            where: { category, status: 'published' },
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['uid', 'username']
                }
            ],
            order: [['createAt', 'DESC']],
            limit: parseInt(limit),
            offset: parseInt(offset)
        });

        ctx.body = {
            code: 200,
            message: '获取分类文章列表成功',
            data: {
                articles,
                total: count,
                page: parseInt(page),
                limit: parseInt(limit),
                totalPages: Math.ceil(count / limit)
            },
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '获取分类文章列表失败',
            error: error.message
        };
    }
});

// 搜索文章
articleRouter.get('/search/:keyword', async (ctx, next) => {
    try {
        const { keyword } = ctx.params;
        const { page = 1, limit = 10 } = ctx.query;
        const offset = (page - 1) * limit;
        const { Op } = require('sequelize');
        
        const { count, rows: articles } = await Article.findAndCountAll({
            where: {
                status: 'published',
                [Op.or]: [
                    { title: { [Op.like]: `%${keyword}%` } },
                    { content: { [Op.like]: `%${keyword}%` } },
                    { summary: { [Op.like]: `%${keyword}%` } },
                    { tags: { [Op.like]: `%${keyword}%` } }
                ]
            },
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['uid', 'username']
                }
            ],
            order: [['createAt', 'DESC']],
            limit: parseInt(limit),
            offset: parseInt(offset)
        });

        ctx.body = {
            code: 200,
            message: '搜索文章成功',
            data: {
                articles,
                total: count,
                page: parseInt(page),
                limit: parseInt(limit),
                totalPages: Math.ceil(count / limit)
            },
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '搜索文章失败',
            error: error.message
        };
    }
});

// 点赞文章
articleRouter.post('/:id/like', async (ctx, next) => {
    try {
        const { id } = ctx.params;
        
        const article = await Article.findByPk(id);
        if (!article) {
            ctx.body = {
                code: 404,
                message: '文章不存在',
                data: null
            };
            return;
        }

        await article.increment('likeCount');

        ctx.body = {
            code: 200,
            message: '点赞成功',
            data: { likeCount: article.likeCount + 1 },
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '点赞失败',
            error: error.message
        };
    }
});

module.exports = articleRouter;
